from flask import request, jsonify
from flask import g
from functools import wraps


def require_login(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        access_token = request.headers.get('ACCESS-TOKEN', None)

        if not access_token:
            return '{"x":"x"}'
        from .auth import AuthsView
        member = AuthsView.get_member_info(access_token)
        if not member:
            return '{"Y":"y"}'
        g.member = member
        return func(*args, **kwargs)

    return decorated_function


def logon_or_abort():
    pass


def current_member():
    return g.member


class APIErrorCode:
    INVALID_PARAMS = 900010


class APIStatus:
    OK = (200, 'Ok')
    CREATED = (201, 'Created')
    BAD_REQUEST = (400, 'Bad request')
    UNAUTHORIZED = (401, 'Unauthorized')
    FORBIDDEN = (403, 'Forbidden')
    NOT_FOUND = (404, 'Not found')


def jsonify_with_success(result, total=None):
    api_status = None
    if request.method == 'POST':
        api_status = APIStatus.CREATED
    else:
        api_status = APIStatus.OK
    resp = {'success': True, 'message': api_status[1], 'result': result}
    if total is not None:
        resp.update(
            {'total': total}
        )
    return jsonify(result), api_status[0]


def jsonify_with_data(status, **kwargs):
    resp = {'data': kwargs, 'message': status[1], 'code': status[0]}
    return jsonify(resp), status[0]


def jsonify_with_error(**kwargs):
    code = kwargs.pop('code', None)
    message = kwargs.pop('message', None)
    resp = (
        {
            'success': False,
            'code': code,
            'message': message
        }
    )
    return jsonify(resp), APIStatus.BAD_REQUEST[0]


def next_id(code=None):
    from ..extensions import next_id
    return next_id(code)
